package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Category;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageBean;
import com.sky.service.CategoryService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SetmealMapper setmealMapper;

    @Autowired
    DishMapper dishMapper;

    @Override
    public List<Category> listCategory(String type) {
        List<Category> categoryList = categoryMapper.listCategory(type);
        return categoryList;
    }

    @Override
    public void addCategory(Category category) {
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
        //category.setStatus(StatusConstant.ENABLE);
        categoryMapper.addCategory(category);
    }

    @Override
    public void updateCategory(Category category) {
//        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateCategory(category);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCategory(String id) {
        // 查询是否关联了套餐
        Integer countNumber = setmealMapper.countCategoryNumber(id);
        if (countNumber > 0) {
          throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        // 查询分类是否关联了菜品
        Integer countDishNumber= dishMapper.countCategoryNumber(id);
        if (countDishNumber > 0) {
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }
        categoryMapper.deleteCategory(id);
    }

    @Override
    public PageBean getPage(String page, String pageSize, String name, String type) {
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(pageSize));

        Page page1 = (Page) categoryMapper.pageCategory(name, type);

        PageBean pageBean = new PageBean();
        pageBean.setRecords(page1.getResult());
        pageBean.setTotal(page1.getTotal());

        return pageBean;

    }

    @Override
    public void updateSatus(String status, Long id) {
        Long currentId = BaseContext.getCurrentId();
        categoryMapper.updateStatus(status, id, currentId);
    }
}
